package com.seven.agent;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;

import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
import java.security.ProtectionDomain;

/**
 * @author xuewenke
 * @since 2022/9/25 9:52 PM
 */
public class MyAgent {

    public static void premain(String arg, Instrumentation instrumentation) {
//        System.err.println("agent startup , args is " + arg);
        // 注册我们的文件下载函数
        instrumentation.addTransformer(new DefineTransformer());
    }

    static class DefineTransformer implements ClassFileTransformer {

        @Override
        public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) {
//            System.out.println("agent load Class:" + className);
//            System.out.println("classBeingRedefined className" + classBeingRedefined.getName());
            if ("com/joinless/businessapp/repository/entity/UserEntity".equals(className)) {
               try {
                   System.out.println("拦截到 " + className);
                   ClassPool classPool = ClassPool.getDefault();
                   System.out.println("classPool = " + classPool);
                   CtClass ctClas = classPool.get("com.joinless.businessapp.repository.entity.UserEntity");
//                   System.out.println("ctClas = " + ctClas);
                   CtMethod toJsonMethod = ctClas.getDeclaredMethod("printJson");
                   toJsonMethod.insertBefore("{System.out.println(\"before toJson method insert\");}");
//                   toJsonMethod.setBody("{return \"toJson 方法已被修改 \" ;}");
                   toJsonMethod.insertAfter("{System.out.println(\"after toJson method insert\");}");

                   byte[] bytes = ctClas.toBytecode();
                   ctClas.detach();
                   return bytes;
               }catch (Exception e) {
                   System.out.println("异常");
                   System.out.println(e.getMessage());
               }

            }

            return null;
        }
    }
    public static void agentmain(String arg, Instrumentation instrumentation) throws ClassNotFoundException, UnmodifiableClassException {
        System.err.println("agent startup , args is " + arg);
        // 注册我们的文件下载函数
        instrumentation.addTransformer(new DefineTransformer(), true);
        Class c = Class.forName("com.joinless.businessapp.repository.entity.UserEntity");
        instrumentation.retransformClasses(c);
    }





}